#include "OpenglAppFramework/inc/OpenglEnv.h"
#include "OpenglAppFramework/inc/Texture.h"
#include "stb_image.h"

#include <iostream>

Texture::Texture() {
    m_is_loaded = false;
}
Texture::~Texture() {}

int Texture::loadAndBind(const std::string& file_name) {
    int ret = 0;
    glGenTextures(1, &m_texture_id);
    glBindTexture(GL_TEXTURE_2D, m_texture_id); 
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    int width, height, nrChannels;
    unsigned char *data = stbi_load(file_name.c_str(), &width, &height, &nrChannels, 0);
    if (data) {
        int pixel_fmt = nrChannels == 3 ? GL_RGB : GL_RGBA;
        glTexImage2D(GL_TEXTURE_2D, 0, pixel_fmt, width, height, 0, pixel_fmt, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
        stbi_image_free(data);
        m_is_loaded = true;
    }
    else {
        std::cerr << "Failed to load texture. file: " << file_name << std::endl;
        ret = -1;
    }
    return ret;
}

unsigned int Texture::getTextureId() const {
    return m_texture_id;
}

bool Texture::isLoaded() const {
    return m_is_loaded;
}
